const app = getApp();
const Controller = require('../../controllers/controllers.js').controller;
const {
  randomNum
} = require('../../../utils/util.js');

const manage = wx.getBackgroundAudioManager()
const SEQUENCE_MODE = 1
const RANDOM_MOD = 2
const SINGLE_CYCLE_MOD = 3

Page({
  /**
   * 页面的初始数据
   */
  data: {
    firstAudioDetaildata: '',
    mode: 1,
    play: 1,
    audioListdata: [],
    compilationId: '',
    ishot: true,
    page: 1,
    pageSize: 10,
    isEnd: false,
    topic: "专题",
    title:'专题详情',
    currentTime: 0,
    playurl: '',
    currentSong: null,
    playMod: SEQUENCE_MODE,
    sortBy:1,
    closetimecurrent:0,
    settimebool: false,
    percent: 0,
    isloading:true,
  },
  onLoad: function (options) {
    console.log(options)
    if (options && options.id) {
      this.setData({
        compilationId: options.id,
        sortBy: options.sortBy || 1
      })
      this.firstAudioDetail(options.id)
      this.audioList(true)
    }
    this.setData({
      playMod: app.globalData.playMod,
      play:app.globalData.play
    })
    if(app.globalData.closetimecurrent>0){
      this.setData({
        closetimecurrent:app.globalData.closetimecurrent,
        settimebool:true
      })
    }
    if(options.scene){
      const id = decodeURIComponent(options.scene);
      console.log(id)
      this.setData({
        compilationId: id
      })
      this.firstAudioDetail(id)
      this.audioList(true)
    }
  },
  firstAudioDetail(id) {
    Controller.compilationDetail({
      compilationId: id,
      token: wx.getStorageSync('logintoken')
    }).then(res => {
      console.log('firstAudioDetail',res)
      this.setData({
        firstAudioDetaildata: res.data.baseData,
        topic: res.data.baseData.title
      })
      wx.setNavigationBarTitle({
        title: res.data.baseData.title
      })
      this.checkCollect()
      
    }).catch(err => {
      console.log(err)
    })
  },
  // 获取列表数据
  audioList(autoplay) {
    Controller.audioList({
      compilationId: this.data.compilationId,
      sortBy: this.data.sortBy,
      page: 1,
      pageSize: 100
    }).then(res => {
      if (res.data.baseData && res.data.baseData.list.length > 0) {
        this.setData({
          audioListdata: res.data.baseData.list
        })
        
      }
      this.setData({isloading:false})
    }).catch(res=>{
      this.setData({isloading:false})
    })
  },
  onPageScroll: function (e) { // 获取滚动条当前位置
    if (e.scrollTop > 20) {
      this.setData({
        defaultFix: true
      })
    } else {
      this.setData({
        defaultFix: false
      })
    }
  },
  mode(e) {
    var mode = e.currentTarget.dataset.mode;
    this.setData({
      mode: mode
    })
  },
  play(e) {
    var play = e.currentTarget.dataset.play;
    this.setData({
      play: play
    })
  },
  hot(e) {
    console.log('hot', e) //sortBy1是最新，2是最热，
    let sortBy = e.currentTarget.dataset.sortby
    this.setData({
      ishot: !this.data.ishot,
      audioListdata: [],
      isloading:true,
      sortBy,
      page: 1,
      isEnd: false,
    })
    this.audioList();
  },
  scrollend() {
    if (this.data.isEnd) {
      return;
    } else {
      this.setData({
        page: this.data.page + 1,
      });
      this.audioList()
    }
  },
  descmore() {
    let that = this
    that.Dialog.ShowDialog({
      title: that.data.firstAudioDetaildata.title,
      content:that.data.firstAudioDetaildata.desc,
      type: 'BottomAlert',
      callback(obj) {
        that.Dialog.CloseDialog();
      }
    })
  },
  playall(e) {
    var index=0;
    if(e.currentTarget.dataset.index){
      index=e.currentTarget.dataset.index
    }
    app.globalData.currentIndex=index
    app.globalData.songlist=this.data.audioListdata
    // this._init()
    wx.navigateTo({
      url: "/pages/Playing/Playing?compilationId=" + this.data.compilationId + "&sortBy="+this.data.sortBy  + "&currentIndex=" + index
    })
  },
  comments(e) {
    app.comments(this.data.firstAudioDetaildata.id, 2)
  },
  share(e) {
    app.share(this.data.firstAudioDetaildata.id, 2, this.data.firstAudioDetaildata.title, this.data.firstAudioDetaildata.imgUrl)
  },
  collect(e) {
    if (!wx.getStorageSync('logintoken')) {
      this.ToLogin()
    }else{
      let data = {
        rid: this.data.firstAudioDetaildata.id || '',
        type: 2,
        bodyId:2
      }
      
      Controller.collect(data).then(res => {
        wx.showToast({
          title: '收藏成功',
          icon: 'success',
          duration: 1500
        })
        this.checkCollect()
        app.updateScore(9)
      })
    }
  },
  checkCollect() {
    Controller.checkCollect({
      rid: this.data.firstAudioDetaildata.id,
      type: 2
    }).then(res => {
      if (res.data && res.data.baseData) {
        this.setData({
          iscollect: true,
          Collectid: res.data.baseData
        })
      } else {
        this.setData({
          iscollect: false
        })
      }
    })
  },
  delcollect(e) {
    var that=this;
    if (!wx.getStorageSync('logintoken')) {
      that.ToLogin()
    }else{
      console.log('用户取消收藏接口')
      wx.showModal({
        title: '提示',
        content: '是否取消收藏?',
        success(res) {
          if (res.confirm) {
            Controller.delCollect({
              ids: that.data.Collectid
            }).then(res => {
              that.checkCollect()
            })
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })
    }
  },
  onReady() {
    this.Dialog = this.selectComponent('#Dialog');
  },
  download(e) {
    let that = this
    that.Dialog.ShowDialog({
      title: '是否下载音频',
      type: 'Confirm',
      callback(obj) {
        console.log('eee', obj)
        if (obj.name == 'confirm') {
          app.download(that.data.firstAudioDetaildata.id)
        }
        that.Dialog.CloseDialog();
      }
    })
  },
  mvlook(e){
    wx.navigateTo({
      url: '/pages/weixinlink/weixinlink?url='+e.currentTarget.dataset.url
    })
  },
  mvmin(e){
    wx.navigateToMiniProgram({
      appId: e.currentTarget.dataset.id,
      path: e.currentTarget.dataset.path,
      extraData: {},
      envVersion: 'release',
      success(res) {
        // 打开成功
      }
    })
  },


  //初始化
  _init() {
    let currentIndex = app.globalData.currentIndex || 0;
    let songslist = (app.globalData.songlist.length && app.globalData.songlist)
    let currentSong = app.globalData.songlist[app.globalData.currentIndex] || (songslist && songslist[app.globalData.currentIndex])
    let duration = currentSong && currentSong.duration
    this.setData({
      currentSong: currentSong,
      duration: duration,
      songslist: songslist,
      currentIndex: currentIndex
    })
    this._getPlayUrl(currentSong)
  },
  // 获取播放地址
  _getPlayUrl(currentSong) {
    const _this = this
    if (currentSong.audioUrl) {
      _this._createAudio(currentSong)
    } else {
      
      manage.stop()
      wx.showToast({
        title: '本歌曲暂时不能播放。请切换下一首',
        icon: 'none'
      })
    }
  },
  // 创建播放器
  _createAudio(currentSong) {
    if(!manage.src){
      manage.src = currentSong.audioUrl
      manage.title = currentSong.title 
      manage.coverImgUrl=currentSong.imgUrl
      // wx.playBackgroundAudio({
      //   dataUrl: currentSong.audioUrl,
      //   title: currentSong.title,
      //   coverImgUrl: currentSong.imgUrl
      // })
      app.updateScore(5,currentSong.id)
    }

    // 监听音乐播放。
    manage.onPlay(()=>{
      this.setData({
        play: 2,
      })
      app.globalData.play = 2
      app.globalData.currentSong = this.data.currentSong
      app.play(this.data.currentSong.id)
    })
    // 监听音乐暂停。
    manage.onPause(()=>{
      this.setData({
        play: 1,
      })
      app.globalData.play = 1
      app.globalData.currentSong = this.data.currentSong
      // 更新收听时长接口
      Controller.uploadListenTimes({
          seconds: parseInt(this.data.currentTime)
        })
        .then(res => {

        })
    })
    
    manage.onEnded(()=>{
      this.setData({
        play: 1,
      })
      app.globalData.play = 1
      app.globalData.currentSong = this.data.currentSong
      Controller.uploadListenTimes({
          seconds: parseInt(this.data.currentTime)
        })
        .then(res => {

        })
      if (this.data.playMod === SINGLE_CYCLE_MOD) {
        this._init(true)
        return
      }

      this.endnext()
    })

    this.onTimeUpdate()
    
  },
  onTimeUpdate(time) {
    // 监听播放拿取播放进度
    if (time) {
      manage.seek(time);
    }
    manage.onTimeUpdate(() => {
      const currentTime = manage.currentTime;
      const duration = manage.duration
      this.setData({
        currentTime: this._formatTime(currentTime),
        duration: this._formatTime(duration),
        percent: currentTime / duration * 100
      })

    })
  },
  // 滑动
  musicchange(e) {
    var current = Number(e.detail.value);
    var duration = this._formatSecod(this.data.duration) || 0;
    var max = 506
    var change = '';
    change = current / max * duration;
    this.onTimeUpdate(change)
  },
  _formatSecod(time) {
    time = time || 0
    if (time) {
      var min = time.split(':')[0];
      var sec = time.split(':')[1];
      var s = Number(min * 60) + Number(sec);
    } else {
      s = 0
    }
    return s
  },

  _formatTime(interval) {
    interval = interval | 0
    const minute = interval / 60 | 0
    const second = this._pad(interval % 60)
    return `${minute}:${second}`
  },
  /*秒前边加0*/
  _pad(num, n = 2) {
    let len = num.toString().length
    while (len < n) {
      num = '0' + num
      len++
    }
    return num
  },
  prev() {
    app.globalData.currentIndex = this.getNextIndex(false)
    this._init()
  },
  next() {
    app.globalData.currentIndex = this.getNextIndex(true)
    this._init()
  },
  changeMod() {
    let playMod = this.data.playMod + 1
    if (playMod > SINGLE_CYCLE_MOD) {
      playMod = SEQUENCE_MODE
    }
    this.setData({
      playMod: playMod
    })
    app.globalData.playMod=playMod
  },
  getNextIndex(nextFlag) {
    let ret,
      currentIndex = app.globalData.currentIndex,
      mod = this.data.playMod,
      len = this.data.songslist.length
    if (mod === RANDOM_MOD) {
      ret = randomNum(len)
    } else {
      if (nextFlag) {
        ret = currentIndex + 1 == len ? 0 : currentIndex + 1
      } else {
        ret = currentIndex - 1 < 0 ? len - 1 : currentIndex - 1
      }
    }
    return ret
  },
  togglePlaying(e) {
    var that=this;

    if(app.globalData.songlist && app.globalData.songlist==that.data.audioListdata){
      wx.getBackgroundAudioPlayerState({
        success(res) {
          var play=1;
          var status = res.status
          if (status == 1) {
            manage.pause()
            play=1
          } else {
            manage.play()
            play=2
          }
          that.setData({
            play:play,
            playcurrent:that.data.current
          })
        }
      })
    }else{
      app.globalData.songlist=that.data.audioListdata
      that._init();
    }
    that.selectComponent('#Footer').playmusic();
    // wx.getBackgroundAudioPlayerState({
    //   success(res) {
    //     var status = res.status
    //     if (status == 1) {
    //       manage.pause()
    //     } else {
    //       manage.play()
    //     }
    //   }
    // })
  },

  bindPickerChange: function (e) {
    var that = this;
    that.Dialog.ShowDialog({
      type: 'Pager',
      callback: res => {
        this.Dialog.CloseDialog();
      }
    })
  },
  toastTime(res){
    var time=res.detail.time;
    var close=res.detail.close;
    if(time>0 && !close){
      this.setData({
        closetimecurrent:time,
        settimebool: true,
      })
    }else{
      if(close){
        this.setData({
          closetimecurrent:0,
          settimebool: false
        })
      }else{
        this.setData({
          closetimecurrent:0,
          settimebool: false,
          play: 1
        })
        manage.pause()
      }
    }
  },
  onShareAppMessage: function (e) {
    // if (e.from == "button") {
      let obj = {
        title: '有氧FM·专题详情',
        success: function (res) {
          
        },
        fail(err) {
          
        }
      }
      return obj
    // }
  },
  onShareTimeline: function (e) {
    // if (e.from == "button") {
      let obj = {
        title: '有氧FM·专题详情',
        success: function (res) {
          
        },
        fail(err) {
          
        }
      }
      return obj
    // }
  },
})